//
//  SceneDelegate.m
//  us
//
//  Created by 李鹏程 on 2025/3/26.
//

#import "SceneDelegate.h"
#import "MainViewController.h"
#import "LoginViewController.h"
#import "USLoveCompassViewController.h"
#import <WXApi.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <AlipaySDK/AlipaySDK.h>


@interface SceneDelegate () <WXApiDelegate>

@end

@implementation SceneDelegate


- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). t
    
    UIWindowScene *windowScene = (UIWindowScene *)scene;
    self.window = [[UIWindow alloc] initWithWindowScene:windowScene];
    
    if (USUser.isLogin) {
        [self setupUsRootController];
    } else {
        [self setupUsLoginController];
    }
    
}

- (void)setupUsLoginController{
    
    DTNavigationController *mainVC = [[DTNavigationController alloc] initWithRootViewController:[LoginViewController new]];
    self.window.rootViewController = mainVC;
    [self.window makeKeyAndVisible];
    
}

- (void)setupUsRootController{
    
    UIViewController *home = [self subControllerWithItemImage:[UIImage imageNamed:@"tabbar-00"] selectedImage:[UIImage imageNamed:@"tabbar-01"] clsssName:@"MainViewController"];
    
    UIViewController *photo = [self subControllerWithItemImage:[UIImage imageNamed:@"tabbar-10"] selectedImage:[UIImage imageNamed:@"tabbar-11"] clsssName:@"USPhotoController"];
    
    UIViewController *chat = [self subControllerWithItemImage:[UIImage imageNamed:@"tabbar-20"] selectedImage:[UIImage imageNamed:@"tabbar-21"] clsssName:@"UIViewController"];
    
//    UIViewController *find = [self subControllerWithItemImage:[UIImage imageNamed:@"tabbar-30"] selectedImage:[UIImage imageNamed:@"tabbar-31"] clsssName:@"USDiscoverViewController"];
    
    UIViewController *set = [self subControllerWithItemImage:[UIImage imageNamed:@"tabbar-40"] selectedImage:[UIImage imageNamed:@"tabbar-41"] clsssName:@"USSetController"];

    USTabBarController *tabBarController = [[USTabBarController alloc]init];
    
    tabBarController.viewControllers = @[home,photo,chat,set];
    
    [self.window setRootViewController:tabBarController];
    [self.window makeKeyAndVisible];
}

- (UIViewController *)subControllerWithItemImage:(UIImage *)image
                                   selectedImage:(UIImage *)selectedImage
                                       clsssName:(NSString *)className{
    
    UIViewController *vc = [NSClassFromString(className) new];
    vc.tabBarItem.image = image;
    vc.tabBarItem.selectedImage = [selectedImage imageWithTintColor:UIColor.blackColor];
    vc.tabBarItem.imageInsets = UIEdgeInsetsMake(0, 0, -12, 0);
    
    DTNavigationController *navc = [[DTNavigationController alloc]initWithRootViewController:vc];
    return navc;
}

- (void)updateChatBadge:(NSInteger)badge{
    UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    if ([tabBarController isKindOfClass:[UITabBarController class]]) {
        UITabBarItem *chatTabItem = tabBarController.tabBar.items[2];
        if (badge == 0) {
            chatTabItem.badgeValue = nil;
        }else {
            chatTabItem.badgeValue = [NSString stringWithFormat:@"%li",badge];
        }
    }
}
- (void)switchToMainInterface {

    [self setupUsRootController];

    [UIView transitionWithView:self.window
                      duration:0.4
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:nil
                    completion:nil];
}

- (void)switchToLoginInterface {

    [self setupUsLoginController];

    [UIView transitionWithView:self.window
                      duration:0.4
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:nil
                    completion:nil];
}

// iOS 13+
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
    UIOpenURLContext *context = URLContexts.anyObject;
    if (!context) return;
    
    NSURL *url = context.URL;
    if ([url.host isEqualToString:@"oauth"]) {
        //微信登录回调
        [WXApi handleOpenURL:context.URL delegate:self];
    }else if ([url.host isEqualToString:@"qzapp"]) {
        [TencentOAuth HandleOpenURL:context.URL];
    }else if ([url.host isEqualToString:@"pay"]) {
        //微信支付回调
        [WXApi handleOpenURL:url delegate:self];
    }else if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:nil];
            NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            NSLog(@"str = %@",str);
            NSString * resultstate =[resultDic objectForKey:@"resultStatus"];
            NSLog(@"reslut = %@",[resultDic objectForKey:@"resultStatus"]);
            if ([resultstate isEqualToString:@"9000"]){
                [[NSNotificationCenter defaultCenter]postNotificationName:@"PaySuccess" object:nil];

            }else{
                
            }
        }];
    }
}
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *authResp = (SendAuthResp *)resp;
        if (authResp.errCode == WXSuccess) {
            NSLog(@"微信登录成功，code = %@", authResp.code);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"WXLogin" object:authResp.code];
        } else {
            NSLog(@"微信登录失败，错误码：%d", authResp.errCode);
        }
    }else if ([resp isKindOfClass:[PayResp class]]){
        PayResp *payResp = (PayResp *)resp;
        if (payResp.errCode == WXSuccess) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"PaySuccess" object:nil];
            NSLog(@"微信支付成功，code = %i", payResp.errCode);
        } else {
            NSLog(@"微信支付失败，错误码：%i", payResp.errCode);
        }
    }
}
- (void)sceneDidDisconnect:(UIScene *)scene {
    // Called as the scene is being released by the system.
    // This occurs shortly after the scene enters the background, or when its session is discarded.
    // Release any resources associated with this scene that can be re-created the next time the scene connects.
    // The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}


- (void)sceneDidBecomeActive:(UIScene *)scene {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];

    if (USUser.user.relStatus == 1 && USUser.user.loginStatus == YES) {
        if ([EMClient sharedClient].isLoggedIn) {
            
            // 获取指定会话 ID 的会话。
            EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:USUser.user.relImUserName type:EMConversationTypeChat createIfNotExist:YES];
            // 获取未读消息数。
            NSInteger unreadCount = conversation.unreadMessagesCount;
            
            [self updateChatBadge:unreadCount];
             
        }
     
    }
}


- (void)sceneWillResignActive:(UIScene *)scene {
    // Called when the scene will move from an active state to an inactive state.
    // This may occur due to temporary interruptions (ex. an incoming phone call).
}


- (void)sceneWillEnterForeground:(UIScene *)scene {
    // Called as the scene transitions from the background to the foreground.
    // Use this method to undo the changes made on entering the background.
}


- (void)sceneDidEnterBackground:(UIScene *)scene {
    // Called as the scene transitions from the foreground to the background.
    // Use this method to save data, release shared resources, and store enough scene-specific state information
    // to restore the scene back to its current state.
}


@end
